const Router = require('koa-router')
const router = new Router()
const bcrypt = require('bcryptjs')
const hashTool = require('../../tool/hash')
const MPerson = require("../../models/Person")
const jwt = require('jsonwebtoken')
const key = require('../../config/db')
const passport = require('koa-passport')
const keyToken = require('../../config/db')

router.get("/person", async (ctx, next) => {
    ctx.status = 200
    ctx.body = {
        msg: "this is personApi data"
    }
})

router.post("/register", async (ctx, next) => {
    ctx.status = 200
    let isHasEmail = await MPerson.find({
        personemail: ctx.request.body.personemail
    })
    let isHasName = await MPerson.find({
        personname: ctx.request.body.personname
    })
    if (isHasEmail.length > 0 || isHasName.length > 0) {
        ctx.status = 500
        ctx.body = {
            msg: "邮箱或用户名已被占用"
        }
    } else {
        const Nperson = new MPerson({
            personemail: ctx.request.body.personemail,
            personname: ctx.request.body.personname,
            // password: ctx.request.body.password
            password: hashTool.getHash(ctx.request.body.password)
        })

        // Nperson.password = await new Promise((resolve, reject) => {
        //     bcrypt.hash(Nperson.password, 10,  (err, hash) => {
        //         if (err) reject(err)
        //         resolve(hash)
        //     });
        // })
        await Nperson.save((err, res) => {
            if (err) throw err
            ctx.body = res
        })
        ctx.body = Nperson
    }

})

router.post('/login', async ctx => {
    let { personname, personemail, password } = ctx.request.body
    const findResult = await MPerson.find({ personname, personemail })
    if (findResult.length > 0) {
        let rolePassword = await bcrypt.compareSync(password, findResult[0].password);
        if (rolePassword) {
            let playload = { id: findResult[0]._id, personname: findResult[0].personname, personemail: findResult[0].personemail }
            let token = jwt.sign(playload, keyToken.keyToken, { expiresIn: 3600 })
            ctx.body = {
                msg: '登陆成功',
                token: 'Bearer ' + token
            }
        } else {
            ctx.status = 400
            ctx.body = {
                msg: '密码错误'
            }
        }
    } else {
        ctx.status = 404
        ctx.body = {
            mag: '没有该用户'
        }
    }
})
// 验证token
router.get('/hasToken', passport.authenticate("jwt", { session: false }), async ctx => {
    ctx.body = {
        id: ctx.state.user._id,
        personname: ctx.state.user.personname,
        personemail: ctx.state.user.personemail
    }
})



// module.exports = router.routes()
module.exports = router